var controller = require('../core/controller.js');
var log = require('../core/log.js');
var enoceanHelper = require('../core/enocean.js');
var fs = require('fs');
var net = require('net');
var config = require('../config.js');

function startListen() {
    var client = net.connect(config.enocean_port, config.enocean_host);
		client.on('connect', function() {
				log.info('source EnOcean', 'connected to the STC-ethernet receiver...');

				//data will be received as strings of 'hex' telegrams
				client.setEncoding('utf8');
				client.on('data', function(data) {
				    //retrieves the first occurence of a valid telegram from data
						var sync = enoceanHelper.synchronize(data);
						while (sync != null) {
						    data = sync.substract;
								var telegram = enoceanHelper.parse(sync.tg);
								if (!telegram) {
								    log.err('source EnOcean', 'cannot parse received telegram');
										return;
								}
								var decoded_data;
								enoceanHelper.isTeachIn(function(exists) {
debugger;
									if (exists) {
debugger;
											//type should be read from 'teachin.json' conf file
											fs.readFile(__dirname + '/../modules/stats/teachin.json', 'utf8', 
												function(err, file) {
													if (err) console.error(err.toString());
													else {
															var teachin = JSON.parse(file);
															enoceanHelper.decodeTeachIn(telegram, teachin, 
																function(decoded) {
																	controller.process_sensor("__teachin", decoded);
																	log.info('source EnOcean', 'data received and processed (teach-in). id sensor: ' + decoded.id);
															});
													}
											});
									} else {
											enoceanHelper.decode(telegram, function(decoded) {
													controller.process_sensor("enocean_" + decoded.id, decoded);
												log.info('source EnOcean', 'data received and processed. id sensor: ' + decoded.id);
											});
									}
								});
								sync = enoceanHelper.synchronize(data);
						}
				});
		});

		client.on('error', function(){
				log.err('source EnOcean', 'cannot connect to the STC-ethernet receiver');
		});
}

module.exports.startListen = startListen;
    
// Exemple d'utilisation du "framework"
   /* var obj_js;
    var id_sensor = 1244243;
    
    obj_js['raw'] = DONNE_BRUTE; // juste la data
    
    obj_js['temperature'] = 12.126;
    
    // Declenche toutes les actions enregistrées pour 
    controller.process_sensor(id_sensor, obj_js);*/
